/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.absisgroup.nsc.home;

import com.absisgroup.nsc.utilities.GenericServlet;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author Hue
 */
public class Categories extends GenericServlet {

    @Override
    public int process(final Connection con, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        
        writeToResponse(response, toJSONObject(con));
        
        return DONT_RUN_JSP;
    }
 
    private String toJSONObject(final Connection con) throws Exception {
        final String strQuery = "Select ncat_pk, ncat_name From nsc_category Order by ncat_name";
        final PreparedStatement pStmt = con.prepareStatement(strQuery);
        final ResultSet rs = pStmt.executeQuery();
        final JSONArray jsArray = new JSONArray();
        while(rs.next()) {
            final JSONObject jsObj = new JSONObject();
            jsObj.put("value", rs.getString("ncat_pk"));
            jsObj.put("name", rs.getString("ncat_name"));
            jsArray.put(jsObj);
        }
        pStmt.close();

        final JSONObject jsObj = new JSONObject();
        jsObj.put("categories", jsArray);
        
        return jsObj.toString();
    }
}
